package com.usian.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.search.dto.UserSearchDto;
import com.usian.search.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Auther:ASS
 * @Date:2023/3/8 19:39
 */
@Service
public class SearchServiceImpl implements SearchService {

        @Autowired
        private RestHighLevelClient restHighLevelClient;

    /**
     * 搜索文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto){



        //校验参数
        if (dto==null ||dto.getMinBehotTime()==null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        List<Map> resultlist=new ArrayList<>();

        try {

            SearchRequest searchRequest=new SearchRequest("app_info_articlez");

            SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

            //组合多条件
            BoolQueryBuilder queryBuilder=QueryBuilders.boolQuery();

            //第一个条件
            QueryStringQueryBuilder queryStringQueryBuilder= QueryBuilders.queryStringQuery(dto.getSearchWords()).
                    field("title").field("content").defaultOperator(Operator.OR);

            //must 条件是 queryBuilder
            queryBuilder.must(queryStringQueryBuilder);

            //第二个条件构建区间查询
            RangeQueryBuilder rangeQueryBuilder=QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime());
            //操作的是第二个条件
            queryBuilder.filter(rangeQueryBuilder);


            searchSourceBuilder.query(queryBuilder);

            //排序
            searchSourceBuilder.sort("publishTime", SortOrder.DESC);


            //分页
            searchSourceBuilder.from(dto.getPageNum());
            searchSourceBuilder.size(dto.getPageSize());



            searchRequest.source(searchSourceBuilder);


            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //查询的到低有没有结果 封装返回

            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();//json串
                Map map = JSON.parseObject(sourceAsString, Map.class);
                resultlist.add(map);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseResult.okResult(resultlist);
    }
}
